package com.eolwral.osmonitor;

import java.io.IOException;
import java.io.InputStream;

public class IOUtils {
	/**
	 * Read entire contents of an @code{InputStream}.
	 *
	 * TODO: There should be a character limit here to prevent memory blowups.
	 *
	 * @param is stream to read from
	 * @return the characters read
	 * @throws IOException
	 */
	public static String readAll(InputStream is) throws IOException {
		// Some benchmarking notes (real hardware vs emulator):
		//
		// On a Galaxy Nexus, this method runs in 0.4 ms per call over 815 calls
		// in 3 process list refreshes.
		//
		// In the emulator, it takes 2.9 ms per call over 464 calls in 4 process
		// list refreshes.

		// Choose this value such that most input streams are shorter than this
		// many bytes. If the particular input stream given satisfies this
		// condition, this function will only make two calls to read(), one to
		// fill the buffer, and another to detect EOF.
		final int BUFFER_SIZE_BYTES = 256;
		byte[] buffer = new byte[BUFFER_SIZE_BYTES];
		StringBuilder result = new StringBuilder();

		for (;;) {
			int numRead = is.read(buffer);
			if (numRead == -1) {
				break;
			}

			result.append(new String(buffer, 0, numRead, "ISO-8859-1"));
		}

		return result.toString();
	}

	/**
	 * Read entire contents of an @code{InputStream}, but return only the
	 * contents up to, but not including, the first null (\0) character.
	 *
	 * @param is stream to read from
	 * @return the characters read, not including the null terminator
	 * @throws IOException
	 */
	public static String readUpToNull(InputStream is) throws IOException {
		String contents = readAll(is);
		int indexOfNull = contents.indexOf('\0');
		if (indexOfNull == -1) {
			return contents;
		} else {
			return contents.substring(0, indexOfNull);
		}
	}
}
